<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Log4j,Slf4j," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="Java日志学习笔记java的日志方案有Commons-logging, Log4j, Slf4j, LogBack…
Commons-logging: apache最早提供的日志的门面接口，类似于jdbc的接口，具体实现由jdbc driver
Log4j:经典的一种日志解决方案，内部把日志系统抽象封装为Logger, appender, pattern等实现，可以通过配置文件轻松的实现日志系统">
<meta property="og:type" content="article">
<meta property="og:title" content="Java日志学习笔记">
<meta property="og:url" content="https://zitongchen.github.io/2017/08/01/Java日志学习笔记/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="Java日志学习笔记java的日志方案有Commons-logging, Log4j, Slf4j, LogBack…
Commons-logging: apache最早提供的日志的门面接口，类似于jdbc的接口，具体实现由jdbc driver
Log4j:经典的一种日志解决方案，内部把日志系统抽象封装为Logger, appender, pattern等实现，可以通过配置文件轻松的实现日志系统">
<meta property="og:updated_time" content="2017-09-16T10:23:16.446Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java日志学习笔记">
<meta name="twitter:description" content="Java日志学习笔记java的日志方案有Commons-logging, Log4j, Slf4j, LogBack…
Commons-logging: apache最早提供的日志的门面接口，类似于jdbc的接口，具体实现由jdbc driver
Log4j:经典的一种日志解决方案，内部把日志系统抽象封装为Logger, appender, pattern等实现，可以通过配置文件轻松的实现日志系统">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/08/01/Java日志学习笔记/"/>





  <title> Java日志学习笔记 | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/08/01/Java日志学习笔记/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java日志学习笔记
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-01T00:00:00+08:00">
                2017-08-01
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2017/08/01/Java日志学习笔记/" class="leancloud_visitors" data-flag-title="Java日志学习笔记">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Java日志学习笔记"><a href="#Java日志学习笔记" class="headerlink" title="Java日志学习笔记"></a>Java日志学习笔记</h1><p>java的日志方案有Commons-logging, Log4j, Slf4j, LogBack…</p>
<p>Commons-logging: apache最早提供的日志的门面接口，类似于jdbc的接口，具体实现由jdbc driver</p>
<p>Log4j:经典的一种日志解决方案，内部把日志系统抽象封装为Logger, appender, pattern等实现，可以通过配置文件轻松的实现日志系统的管理和多样化配置</p>
<p>Slf4j:全称：Simple Logging Facade for JAVA : java简单日志门面，是对不同日志框架提供的一种门面封装，部署的时候不修改任何配置即可接入一种日志实现方案。</p>
<p>Logback: 作为一个通用可靠，快速灵活的日志框架，将作为Log4j的替代和Slf4j组合新的日志系统的完整实现</p>
<h2 id="SLF4J日志方案"><a href="#SLF4J日志方案" class="headerlink" title="SLF4J日志方案"></a>SLF4J日志方案</h2><p>通过SLF4J依赖，提供日志API，其实使用Log4J作为实现的，其Maven的配置如下：</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.slf4j<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></div><div class="line">  	<span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>slf4j-log4j12<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></div><div class="line">  	<span class="tag">&lt;<span class="name">version</span>&gt;</span>1.7.7<span class="tag">&lt;/<span class="name">version</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></div></pre></td></tr></table></figure>
<p>若是在Maven工程中，必须在main/resource目录下创建一个名为<code>log4j.properties</code>的文件,内容如下：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">#日志级别为ERROR 提供两种日志console(控制台),file(文本)</div><div class="line">#需要对两种日志分别配置</div><div class="line"></div><div class="line">log4j.rootLogger = ERROR, console, file</div><div class="line">#控制台日志</div><div class="line">log4j.appender.console = org.apache.log4j.ConsoleAppender</div><div class="line">log4j.appender.console.layout = org.apache.log4j.PatternLayout</div><div class="line"># %m%n在日记结尾添加换行</div><div class="line">log4j.appender.console.layout.ConversionPattern = %m%n  </div><div class="line"></div><div class="line">#文件日志</div><div class="line">log4j.appender.file = org.apache.log4j.DailyRollingFileAppender</div><div class="line">#输出日志到指定的文件</div><div class="line">log4j.appender.file.File = $&#123;user.home&#125;/logs/book.log</div><div class="line">#文件回滚的时间</div><div class="line">log4j.appender.file.DatePattern = &apos;_&apos;yyyyMMdd </div><div class="line">log4j.appender.file.layout = org.apache.log4j.PatternLayout</div><div class="line">log4j.appender.file.layout.ConversionPattern = %d&#123;HH:mm:ss,SSS&#125; %p %c (%L) - %m%m</div><div class="line"></div><div class="line">#同时指定只有cc.codingape包下的类才输出DEBUG级别的日志</div><div class="line">log4j.logger.cc.codingape = DEBUG</div></pre></td></tr></table></figure>
<p>日志的一个使用范例：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">import</span> org.slf4j.Logger;</div><div class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Slf4jDemo</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger LOGGER = LoggerFactory.getLogger(Slf4jDemo.class);</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</div><div class="line">        LOGGER.error(<span class="string">"Slf4jDemo"</span>);<span class="comment">//在控制台上输出Slf4jDemo</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在Slf4j中增加了占位符{},使得信息的输出便捷很多</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">import</span> org.slf4j.Logger;</div><div class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Slf4jDemo</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger LOGGER = LoggerFactory.getLogger(Slf4jDemo.class);</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</div><div class="line">        String message = <span class="string">"slf4j"</span>;</div><div class="line">        LOGGER.debug(<span class="string">"use &#123;&#125;"</span>,message);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="日志的配置文件"><a href="#日志的配置文件" class="headerlink" title="日志的配置文件"></a>日志的配置文件</h2><h3 id="核心对象"><a href="#核心对象" class="headerlink" title="核心对象"></a>核心对象</h3><ul>
<li>Logger对象  负责获取日志信息，并存储于一个分层的命名空间中</li>
<li>Layout对象   提供用于各种风格格式的日志信息的对象，在日志发布前，为appender提供支持</li>
<li>Appender对象   负责将日志信息发布到不同的目的地，比如数据库，文件， 控制台</li>
</ul>
<p>%m%n`表示在输出信息后换行</p>
<p>日志的级别有：TRACE &lt; DEBUG &lt; INFO &lt; WARN &lt; ERROR &lt; FATAL &lt; ALL 级别不断提高，输出的日志基本高于配置文件中日志的基本才能得以输出，例如配置文件中的日志级别为 ERROR，则代码中INFO级别的日志是无法输出的，FATAL,ALL级别的日志信息才能被输出。<code>若指定具体包下的日志输出级别除外</code>，如上述<code>log4j.logger.cc.codingape = DEBUG</code>指定了<code>cc.codingape</code>包下的日志输出级别为DEBUG.</p>
<p>在日志的配置文件中可以使用<code>${}</code>的运算符来配置文件</p>
<h3 id="Layout类型"><a href="#Layout类型" class="headerlink" title="Layout类型"></a>Layout类型</h3><p>Apache Log4j提供多个Layout对象，每个根据布局的不同都可格式化日志数据</p>
<ul>
<li>DateLayout</li>
<li>HTMLLayout</li>
<li>PatternLayout</li>
<li>SimpleLayout</li>
<li>XMLLayout</li>
</ul>
<h3 id="文件记录日志"><a href="#文件记录日志" class="headerlink" title="文件记录日志"></a>文件记录日志</h3><h4 id="FileAppender配置"><a href="#FileAppender配置" class="headerlink" title="FileAppender配置"></a>FileAppender配置</h4><table>
<thead>
<tr>
<th>属性</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>immediateFlush</td>
<td>默认为true,每次日志追加操作都刷新到文件</td>
</tr>
<tr>
<td>encoding</td>
<td>编码，默认情况下使用平台相关的编码</td>
</tr>
<tr>
<td>threshold</td>
<td>appender对象的阀值</td>
</tr>
<tr>
<td>Filename</td>
<td>日志文件名</td>
</tr>
<tr>
<td>fileAppend</td>
<td>默认true，日志追加到文件</td>
</tr>
<tr>
<td>bufferedIO</td>
<td>是否打开缓冲，默认为false</td>
</tr>
<tr>
<td>bufferSize</td>
<td>若是开启缓冲去IO，指定缓冲区大小，默认8kb</td>
</tr>
</tbody>
</table>
<p>使用<code>org.apache.Log4j.FileAppender</code>将日志记录到文件,</p>
<p>将文件写入多个文件则使用<code>org.apache.Log4j.RollingFileAppender</code>,该类继承了<code>FileAppender</code>类</p>
<h4 id="逐日生成日志"><a href="#逐日生成日志" class="headerlink" title="逐日生成日志"></a>逐日生成日志</h4><p>逐日生成日志文件，使用<code>org.apache.Log4j.DailyRollingFileAppender</code>,该类同样继承了<code>FileAppender</code>类</p>
<p>DatePattern：该属性表明什么时候回滚文件，以及文件的命名约定，缺省情况下每日午夜回滚文件</p>
<table>
<thead>
<tr>
<th>DatePattern</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>‘.’yyyy-MM</td>
<td>在本月末，下月初回滚文件</td>
</tr>
<tr>
<td>‘.’yyyy-MM-dd</td>
<td>在每日午夜回滚文件，缺省值</td>
</tr>
<tr>
<td>‘.’yyyy-MM-dd-a</td>
<td>在每日中午和午夜回滚文件</td>
</tr>
<tr>
<td>‘.’yyyy-MM-dd-HH</td>
<td>在每个整点回滚文件</td>
</tr>
<tr>
<td>‘.’yyyy-MM-dd-HH-mm</td>
<td>每分钟回滚文件</td>
</tr>
<tr>
<td>‘.’yyyy-ww</td>
<td>根据地域，在每周的第一天回滚文件</td>
</tr>
</tbody>
</table>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Log4j/" rel="tag"># Log4j</a>
          
            <a href="/tags/Slf4j/" rel="tag"># Slf4j</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/04/12/Hexo的NexT主题样式美化/" rel="next" title="Hexo的NexT主题优化">
                <i class="fa fa-chevron-left"></i> Hexo的NexT主题优化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/05/Java单元测试框架-JUnit4/" rel="prev" title="Java单元测试框架-JUnit4">
                Java单元测试框架-JUnit4 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Java日志学习笔记"><span class="nav-number">1.</span> <span class="nav-text">Java日志学习笔记</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#SLF4J日志方案"><span class="nav-number">1.1.</span> <span class="nav-text">SLF4J日志方案</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#日志的配置文件"><span class="nav-number">1.2.</span> <span class="nav-text">日志的配置文件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#核心对象"><span class="nav-number">1.2.1.</span> <span class="nav-text">核心对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Layout类型"><span class="nav-number">1.2.2.</span> <span class="nav-text">Layout类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文件记录日志"><span class="nav-number">1.2.3.</span> <span class="nav-text">文件记录日志</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#FileAppender配置"><span class="nav-number">1.2.3.1.</span> <span class="nav-text">FileAppender配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#逐日生成日志"><span class="nav-number">1.2.3.2.</span> <span class="nav-text">逐日生成日志</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
